package service

import (
	"context"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/knowledgePoint/glb"
	"google.golang.org/grpc/metadata"
	"gorm.io/gorm"
)

func (s *Service) CreateKnowledgePoint(ctx context.Context, request *pb.CreateKnowledgePointRequest) (*pb.CreateKnowledgePointResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.CreateKnowledgePointResponse{Status: &pb.ResponseStatus{
			Code: pb.ResponseStatusCode_NotAuth, Message: err.Error(),
		}}, nil
	}

	if !token.IsManager {
		chapter := &models.ChapterModel{UUID: request.GetChapterUUID()}
		err = glb.DB.Select("uuid").Take(chapter, chapter).Error
		if err != nil {
			if err == gorm.ErrRecordNotFound {
				return &pb.CreateKnowledgePointResponse{Status: &pb.ResponseStatus{
					Code:    pb.ResponseStatusCode_OtherError,
					Message: "章节不存在",
				}}, nil
			}
			glb.Logger.Error(err.Error())
			return createKnowledgePointRespSvrErr, nil
		}
		managers := make([]models.UserModel, 0, 1)
		err = glb.DB.Model(chapter).Association("Managers").Find(&managers, "manager_id = ?", token.AccountID)
		if err != nil {
			glb.Logger.Error(err.Error())
			return createKnowledgePointRespSvrErr, nil
		}
		if len(managers) == 0 {
			return &pb.CreateKnowledgePointResponse{Status: &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_NotAuth,
				Message: "用户没有权限",
			}}, nil
		}
	}

	knowledgePoint := &models.KnowledgePoint{
		Name:        request.GetName(),
		ChapterUUID: request.GetChapterUUID(),
	}

	err = glb.DB.Create(knowledgePoint).Error
	if err != nil {
		if core.IsForeignKeyErr(err) {
			return &pb.CreateKnowledgePointResponse{Status: &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "章节不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return createKnowledgePointRespSvrErr, nil
	}

	return &pb.CreateKnowledgePointResponse{
		Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_Success},
		UUID:   knowledgePoint.UUID,
	}, nil
}
